<template>
  <div class="map-wrapper">
    <div id="mapContainers" ref="mapContainers" class="map-container"></div>
  </div>
</template>

<script>
  import 'ol/ol.css';
  import Map from 'ol/Map';
  import OSM from 'ol/source/OSM';
  import XYZ from 'ol/source/XYZ';
  import VectorSource from 'ol/source/Vector';
  import Tile from 'ol/layer/Tile';
  import VectorLayer from 'ol/layer/Vector';
  import Style from 'ol/style/Style';
  import Stroke from 'ol/style/Stroke';
  import Icon from 'ol/style/Icon';
  import View from 'ol/View';
  import Feature from 'ol/Feature';
  import Overlay from 'ol/Overlay';
  import { Point, LineString } from 'ol/geom';
  import { get as getProj, fromLonLat } from 'ol/proj';
  import { ZoomSlider, Zoom } from 'ol/control';
  import { containsCoordinate } from 'ol/extent';

  import { v4 } from 'uuid'

  let olMap = null;

  export default {
    name: 'MapComponent',
    data() {
      return {
        trackLayer: null  // 新增：轨迹图层引用
      };
    },
    created() {
      // this.$nextTick(() => {
      //   setTimeout(() => {
      //     this.init()
      //   }, 100)
      // })
    },
    props: {
      mapParam: {
        type: Object,
        default: () => ({
          center: [119.41020, 39.915119], // 默认中心点（北京）
          zoom: 10,                        // 默认缩放级别
          maxZoom: 19,
          minZoom: 1,
          tilesUrl: undefined              // 默认无自定义瓦片地址
        })
      }
    },
    mounted() {
      setTimeout(() => {
        this.init([{
          longitude: 116.41020,
          latitude: 39.915119
        }]);
      }, 100)
    },
    methods: {
      init(data) {
        let dataCenter = [116.41020, 39.915119]
        console.log(data);

        if (data) {
          dataCenter = [data[0].longitude, data[0].latitude];
        }

        let center = fromLonLat(dataCenter);
        const view = new View({
          center,
          zoom: this.mapParam.zoom || 10,  // 修复
          projection: this.projection,
          maxZoom: this.mapParam.maxZoom || 19,  // 修复
          minZoom: this.mapParam.minZoom || 1,  // 修复
        });
        let tileLayer = null;
        if (mapParam.tilesUrl) {
          tileLayer = new Tile({
            source: new XYZ({
              projection: getProj("EPSG:3857"),
              wrapX: false,
              tileSize: 256 || mapParam.tileSize,
              url: mapParam.tilesUrl
            })
          })
        } else {
          tileLayer = new Tile({
            preload: 4,
            source: new OSM(),
          })
        }
        olMap = new Map({
          target: this.$refs.mapContainers, // 容器ID
          layers: [tileLayer], // 默认图层
          view: view,  // 视图
          controls: [   // 控件
            // new ZoomSlider(),
            new Zoom(),
          ],
        })

        // 添加轨迹点（例如实时位置更新）
        this.addTrackPoints([
          [data[0].longitude, data[0].latitude],
          [data[data.length - 1].longitude, data[data.length - 1].latitude]
        ]);
        // this.addTrackPoint([116.41020, 39.915119]);  // 北京坐标
        // this.addTrackPoint([116.5, 39.9]);  // 新增轨迹点
        // 定位到指定位置
        const that = this
        setTimeout(() => {
          that.locate([data[0].longitude, data[0].latitude], 15);
        }, 500);
      },
      addTrackPoints(points) {
        if (Array.isArray(points)) {
          points.forEach(point => {
            this.addTrackPoint(point);  // 按顺序调用单点添加方法
          });
        }
      },
      addTrackPoint(point) {
        if (!this.trackLayer) {
          // 初始化轨迹图层
          this.trackLayer = new VectorLayer({
            source: new VectorSource(),
            style: new Style({
              stroke: new Stroke({
                width: 4,
                color: "#40a9ff"  // 轨迹线
              })
            })
          });
          olMap.addLayer(this.trackLayer);
        }

        const source = this.trackLayer.getSource();
        const features = source.getFeatures();

        if (features.length === 0) {
          // 首次添加点：创建基础线段
          const line = new LineString([fromLonLat(point)]);
          source.addFeature(new Feature(line));
        } else {
          // 后续添加点：扩展现有线段
          const lineFeature = features[0];
          const line = lineFeature.getGeometry();
          line.appendCoordinate(fromLonLat(point));  // 追加新坐标
          source.updateFeature(lineFeature);  // 更新要素
        }
      },

      // 新增：定位到指定坐标（自动调整视野）
      locate(coordinate, zoom) {
        const mapView = olMap.getView();
        const target = fromLonLat(coordinate);
        const duration = 800;

        mapView.cancelAnimations();
        // 平滑移动到目标位置
        mapView.animate({
          center: target,
          duration: duration
        });

        // 若目标不在当前视野内，调整缩放
        if (!containsCoordinate(mapView.calculateExtent(), target)) {
          mapView.animate({
            zoom: mapView.getZoom() - 1,
            duration: duration / 2
          }, {
            zoom: zoom || mapView.getZoom(),
            duration: duration / 2
          });
        }
      },
      setCenter(point) {

      },
      zoomIn(zoom) {

      },
      zoomOut(zoom) {

      },
      centerAndZoom(point, zoom, callback) {
        var zoom_ = olMap.getView().getZoom();
        zoom = zoom || zoom_;
        var duration = 600;
        olMap.getView().setCenter(fromLonLat(point))
        olMap.getView().animate({
          zoom: zoom,
          duration: duration
        });
      },
      panTo(point, zoom) {
        let duration = 800;

        olMap.getView().cancelAnimations()
        olMap.getView().animate({
          center: fromLonLat(point),
          duration: duration
        });
        if (!containsCoordinate(olMap.getView().calculateExtent(), fromLonLat(point))) {
          olMap.getView().animate({
            zoom: olMap.getView().getZoom() - 1,
            duration: duration / 2
          }, {
            zoom: zoom || olMap.getView().getZoom(),
            duration: duration / 2
          });
        }

      },
      fit(layer) {
        let extent = layer.getSource().getExtent();
        if (extent) {
          olMap.getView().fit(extent, {
            duration: 600,
            padding: [100, 100, 100, 100]
          });
        }


      },
      openInfoBox(position, content, offset) {
        let id = v4()
        // let infoBox = document.createElement("div");
        // infoBox.innerHTML = content ;
        // infoBox.setAttribute("infoBoxId", id)
        let overlay = new Overlay({
          id: id,
          autoPan: true,
          autoPanAnimation: {
            duration: 250
          },
          element: content,
          positioning: "bottom-center",
          offset: offset,
          // className:overlayStyle.className
        });
        olMap.addOverlay(overlay);
        overlay.setPosition(fromLonLat(position));
        return id;
      },
      closeInfoBox(id) {
        olMap.getOverlayById(id).setPosition(undefined)
        // olMap.removeOverlay(olMap.getOverlayById(id))
      },
      /**
       * 添加图层
       * @param data
       * [
       *     {
       *
       *         position: [119.1212,45,122],
       *             image: {
       *                 src:"/images/123.png",
       *                 anchor: [0.5, 0.5]
       *
       *             }
       *     }
       *
       * ]
       */
      addLayer(data, clickEvent) {
        let style = new Style();
        if (data.length > 0) {
          let features = [];
          for (let i = 0; i < data.length; i++) {
            let feature = new Feature(new Point(fromLonLat(data[i].position)));
            feature.customData = data[i].data;
            let cloneStyle = style.clone()
            cloneStyle.setImage(new Icon({
              anchor: data[i].image.anchor,
              crossOrigin: 'Anonymous',
              src: data[i].image.src,
            }))
            feature.setStyle(cloneStyle)
            features.push(feature);
          }
          let source = new VectorSource();
          source.addFeatures(features);
          let vectorLayer = new VectorLayer({
            source: source,
            style: style,
            renderMode: "image",
            declutter: false
          })
          olMap.addLayer(vectorLayer)
          if (typeof clickEvent == "function") {
            olMap.on("click", (event) => {
              vectorLayer.getFeatures(event.pixel).then((features) => {
                if (features.length > 0) {
                  let items = []
                  for (let i = 0; i < features.length; i++) {
                    items.push(features[i].customData)
                  }
                  clickEvent(items)
                }
              })


            })
          }

          return vectorLayer;
        }
      },
      removeLayer(layer) {
        olMap.removeLayer(layer)
      },

      addLineLayer(positions) {
        if (positions.length > 0) {
          let points = [];
          for (let i = 0; i < positions.length; i++) {
            points.push(fromLonLat(positions[i]));
          }
          let line = new LineString(points)
          let lineFeature = new Feature(line);
          lineFeature.setStyle(new Style({
            stroke: new Stroke({
              width: 4,
              color: "#0c6d6a",
            })
          }))
          let source = new VectorSource();
          source.addFeature(lineFeature);
          let vectorLayer = new VectorLayer({
            source: source,
          })
          olMap.addLayer(vectorLayer)
          return vectorLayer;
        }
      }
    },
    destroyed() {
      // if (this.jessibuca) {
      //   this.jessibuca.destroy();
      // }
      // this.playing = false;
      // this.loaded = false;
      // this.performance = "";
    },
  }
</script>


<style scoped>
.map-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.map-container {
  width: 100%;
  height: 100%;
  border-radius: 25px;
  overflow: hidden;
  transform: scale(0.94);
}
</style>